﻿using MediatR;
using SheepCultivation.Common.Domain.main;
using SheepCultivation.Common.Domain.Week2;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;

namespace SheepCultivation.API.AddliCation.Tip_newspaper
{
    public class TransplantingCreateHandler: IRequestHandler<TransplantingCreateCommon, Result>
    {
        public readonly IBaseRepository<Descendent> DescendentRepository;
        public TransplantingCreateHandler(IBaseRepository<Descendent> descendentRepository)
        {
            DescendentRepository = descendentRepository;
        }

        public async Task<Result> Handle(TransplantingCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.error };
            try
            {
                var a = DescendentRepository.GetAll().Where(x => x.breedingSheepArchiveId == request.breedingSheepArchiveId).ToList();
                if (a.Count() == 0)
                {
                    var res = new Descendent()
                    {
                        breedingSheepArchiveId = request.breedingSheepArchiveId,
                        TransplantingDate = request.TransplantingDate,
                        BuildingsEnter = request.BuildingsEnter,
                        ColumnsEnter = request.ColumnsEnter,
                        BuildingId = 0,
                        ColumnsId = 0,
                        Sex = request.Sex,
                        Age = request.Age,
                    };
                    DescendentRepository.Add(res);
                }
                else
                {
                    foreach (var item in a)
                    {
                        item.BuildingId = DescendentRepository.GetAll().Where(x => x.breedingSheepArchiveId == request.breedingSheepArchiveId).FirstOrDefault().BuildingsEnter;
                        item.ColumnsId = DescendentRepository.GetAll().Where(x => x.breedingSheepArchiveId == request.breedingSheepArchiveId).FirstOrDefault().ColumnsEnter;
                        item.breedingSheepArchiveId = request.breedingSheepArchiveId;
                        item.TransplantingDate = request.TransplantingDate;
                        item.BuildingsEnter = request.BuildingsEnter;
                        item.ColumnsEnter = request.ColumnsEnter;
                        item.Sex = request.Sex;
                        item.Age = request.Age;
                        DescendentRepository.Update(item);
                    }
                }
                result.Code = (int)CommonEnumCode.success;
                result.Msg = "后裔转种新增成功";
            }
            catch (Exception ex)
            {

                result.Msg = "后裔转种新增失败";
            }
            return result;
        }
    }
}
